<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/29
 * Time: 13:50
 */

namespace App\Http\Controllers\Api\Record;

use App\Http\Controllers\ApiController;
use App\LogicService\Contracts\MedicalRecordLogicContract;
use App\Models\Doctor;
use App\Models\Hospital;
use App\Models\MedicalAuxiliary;
use App\Models\MedicalComplaint;
use App\Models\MedicalRecord;
use App\Models\PastHistory;
use App\Models\UserBase;
use Carbon\Carbon;
use Illuminate\Http\Request;

class MedicalRecordController extends ApiController
{
    /**
     * @var \Illuminate\Http\Request
     */
    protected $request;

    protected $medicalRecord;

    public function __construct(Request $request, MedicalRecordLogicContract $medicalRecord)
    {
        parent::__construct();

        $this->request = $request;
        $this->medicalRecord = $medicalRecord;
    }

    /**
     * 创建首诊病历
     * @return \Illuminate\Http\JsonResponse
     */
    public function store()
    {
        $input = $this->request->input();

        $input['visit_type'] = 1;
        $input['clinic_at'] = Carbon::now()->toDateString();

        $hospital_id = $this->request->input('hospital_id');
        $patient_id = $this->request->input('patient_id');

        $record = MedicalRecord::where([['hospital_id', '=', $hospital_id], ['patient_id', '=', $patient_id], ['visit_type', '=', 1], ['is_del', '=', 0]])->first();

        if ($record) {
            return $this->setMessage('患者已经在此医院有首诊')->setCode(40300)->hasNoData();
        }
        $result = MedicalRecord::create($input);

        return $this->response(['id' => $result['id']]);
    }


    /**
     * 创建复诊病历
     * @return \Illuminate\Http\JsonResponse
     */
    public function subsequent()
    {
        $input = $this->request->input();

        $input['visit_type'] = 0;
        $input['clinic_at'] = Carbon::now()->toDateString();

        $result = MedicalRecord::create($input);

        return $this->response(['id' => $result['id']]);
    }

    public function delete()
    {
        $this->validate($this->request, [
            'record_id' => 'required|integer|min:1',
            'hospital_id' => 'integer|min:1'
        ]);

        $record_id = $this->request->input('record_id');
        $hospital_id = $this->request->input('hospital_id');

        $user = \Auth::user();
        $record = MedicalRecord::withoutGlobalScope('hasBindDoctor')->findOrFail($record_id);

        if ($user->id != $record->patient_id) {
            return $this->setMessage('不能删除其他人病例')->setCode(40300)->hasNoData();
        }

        if ($record->isFirstVisit() && MedicalRecord::where(['patient_id' => \Auth::id(), 'visit_type' => 0, 'hospital_id' => $hospital_id, 'is_del' => 0])->count()) {
            return $this->setMessage('删除全部本医院复诊后才能删除首诊。')->setCode(40300)->hasNoData();
        }

        return $this->responseForDelete($this->deleteWithRelation($record));
    }

    /**
     * @param \App\Models\MedicalRecord $record
     * @return boolean
     */
    protected function deleteWithRelation(MedicalRecord $record)
    {
        return \DB::transaction(function () use ($record) {
            $record->is_del = 1;
            $record->save();
            return true;
        });
    }

    public function getListByDoctorHospitalId()
    {
        $this->validate($this->request, ['patient_id' => 'required|integer|min:1']);
        $doctor = \Auth::user();
        $patient_id = $this->request->input('patient_id');

        $records = $this->medicalRecord->getListByHospitalId($patient_id, $doctor->hospital_id);

        return $this->response($records);
    }


    public function getListByHospital()
    {
        $patient_id = \Auth::id();

        $records = $this->medicalRecord->getList($patient_id);

        $hospitals = [];
        $result = array();
        if ($records) {
            foreach ($records as $key => $value) {
                if ($value['hospital_id']) {
                    $hospitals[] = $value['hospital_id'];
                }
            }
            if ($hospitals) {
                $hospital_list = Hospital::whereIn('id', $hospitals)
                    ->select('id as hospital_id', 'name')
                    ->get()
                    ->toArray();


                foreach ($hospital_list as $key => &$value) {
                    foreach ($records as $keys => $values) {
                        if ($value['hospital_id'] == $values['hospital_id']) {
                            if ($values['doctor_id']) {
                                $values['doctor'] = UserBase::where('id', $values['doctor_id'])->select('id', 'name')->first()->toArray();
                            }
                            $value['records'][] = $values;
                        }

                    }
                    $result[] = $value;
                }

            }

            $null_records = array();
            foreach ($records as $key => $value) {
                if (!$value['hospital_id']) {
                    $null_records[] = $value;
                }
            }
            if ($null_records) {
                $result[]['records'] = $null_records;
            }

        }

        return $this->response($result);
    }

}